package org.pybaldaj.bot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.pybaldaj.IField;
import org.pybaldaj.util.FileLinesIterator;

public abstract class DictionaryIndex {

	private Map<String, Set<String>> index = new HashMap<String, Set<String>>();
	private List<String> shortWords = new LinkedList<String>();

	private static final int INDEX_DEPTH = 4;
	
	public DictionaryIndex(InputStream in) throws IOException {
		for (String word: new FileLinesIterator(new BufferedReader(new InputStreamReader(in)))) {
			if (word.length() < INDEX_DEPTH) {
				shortWords.add(word);
			}
			for (int i = 0; i < word.length() - INDEX_DEPTH + 1; i++) {
				String key = word.substring(i, i + INDEX_DEPTH);
				if (!index.containsKey(key)) {
					index.put(key, new TreeSet<String>());
				}
				index.get(key).add(word.toLowerCase());
			}
		}
	}
	
	public Iterable<String> getProbableWords(IField f) {
		SortedSet<String> res = new TreeSet<String>();
		for (String key : getAvailableKeys(f)) {
			key = key.toLowerCase();
			if (index.containsKey(key)) {
				res.addAll(index.get(key));
			}
		}
		res.addAll(shortWords);
		return res;
	}
	
	protected abstract Iterable<String> getAvailableKeys(IField f);
	
}
